//
//  MasterViewController.m
//  PrintFactory
//
//  Created by edaihua on 16/2/26.
//  Copyright © 2016年 ___PrintFactory___. All rights reserved.
//

#import "MasterViewController.h"
#import "PhotoPickerCollectionViewController.h"
#import "PFPhotoUploadViewController.h"
#import "PFPrintManager.h"
#import "PhotoResizerViewController.h"
#import "PhotoListTableViewCell.h"
#import "PFDefaultUserConfig.h"
#import "PFPhotoRectManager.h"
#import "PFCommonRectManager.h"
#import "PFPhoto.h"
#import "UILabel+PhotoCount.h"

@interface MasterViewController () <MasterTableViewCellDelegate>
@property (strong, nonatomic) IBOutlet UIView *bottomView;

@property (strong, nonatomic) IBOutlet UIButton *leftBarButton;
@property (strong, nonatomic) IBOutlet UIButton *rightBarButton;

@property (strong, nonatomic) IBOutlet UILabel *photoCountLabel;

@end

@implementation MasterViewController
@synthesize photosManager;

typedef NS_ENUM(NSUInteger, MasterTableCellType) {
    CellTypePhotoType,
    CellTypePhotos,
    CellTypeFooter, // Footer is needed, otherwise the height of master table will be incorrect
    CellTypeNumber
};

const CGFloat cellSpace = 10.0;
const CGFloat bottomBarHeight = 46.0;

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.

    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:self.rightBarButton];
    
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:self.leftBarButton];
    
    [self.navigationController.navigationBar setBarTintColor:[UIColor colorWithRed:103.0/255.0 green:103.0/255.0 blue:103.0/255.0 alpha:1.0]];
    
    self.detailViewController = (DetailViewController *)[[self.splitViewController.viewControllers lastObject] topViewController];
    
    CGRect bottomFrame = self.bottomView.frame;
    CGSize screenSize = [UIScreen mainScreen].bounds.size;
    bottomFrame.origin.x = 0;
    bottomFrame.origin.y = screenSize.height - bottomBarHeight;
    bottomFrame.size.width = screenSize.width;
    bottomFrame.size.height = bottomBarHeight;
    self.bottomView.frame = bottomFrame;
    
    self.commonRectManager = [[PFCommonRectManager alloc] initWithType:[PFPrintManager getCurrentType] boarder:PhotoBoarder_White];
    
    NSString *vcode = @"111111";
    
    [AppDelegate.engine loginWithName:@"13761868036" vcode:[vcode md5] onSucceeded:^{
        NSLog(@"Login succeed");
    } onError:^(NSError *engineError) {
        NSLog(@"Login failed, %@", engineError);
    }];
}

- (void)viewWillAppear:(BOOL)animated {
    self.clearsSelectionOnViewWillAppear = self.splitViewController.isCollapsed;
    [self.photoCountLabel updateWithPhotoCount:[self.photosManager getPhotoCount]];
    [super viewWillAppear:animated];
}

- (void)viewDidAppear:(BOOL)animated {
    
    [UIView animateWithDuration:3.0 animations:^{
        [[[UIApplication sharedApplication] keyWindow] addSubview:self.bottomView];
    }];
}

- (void)viewWillDisappear:(BOOL)animated {
    [self.bottomView removeFromSuperview];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - Segues

- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    if ([[segue identifier] isEqualToString:@"showOrderList"]) {
        PFPhotoUploadViewController *vc = [segue destinationViewController];
        vc.photosManager = self.photosManager;
        
    } else if ([[segue identifier] isEqualToString:@"showPhotoPicker"]) {
        
        PhotoPickerCollectionViewController *photoPicker = (PhotoPickerCollectionViewController*)[segue destinationViewController];
        photoPicker.photosManager = self.photosManager;
        photoPicker.rectManager  = self.commonRectManager;
    }
}


#pragma mark - Table View
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return CellTypeNumber;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    NSInteger numberOfRows = 1;
    if (section == CellTypePhotos) {
        numberOfRows = [self.photosManager getPhotoCount];
    }
    return numberOfRows;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section == CellTypePhotoType) {
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"Header" forIndexPath:indexPath];
        return cell;
        
    } else if (indexPath.section == CellTypePhotos) {
        PhotoListTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"Cell" forIndexPath:indexPath];
        PFPhoto *photo = [self.photosManager getPhotoAtIndex:indexPath.row];
        [cell initWithPhoto:photo delegate:self andPrintType:[PFPrintManager getCurrentType]];
        return cell;
        
    } else if (indexPath.section == CellTypeFooter) {
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"Footer" forIndexPath:indexPath];
        return cell;
    } else {
        return nil;
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    CGFloat cellHeight;
    
    if (indexPath.section == CellTypePhotoType) {
        cellHeight = 107.0;
    } else if (indexPath.section == CellTypePhotos) {
        cellHeight = [PFCommonRectManager getMasterCellSizeWithType:[PFPrintManager getCurrentType]].height;
    } else if (indexPath.section == CellTypeFooter) {
        cellHeight = bottomBarHeight;
    } else {
        NSLog(@"Unknown cell section !");
    }
    
    return cellHeight;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    
    if (indexPath.section == CellTypePhotoType) {
        [self performSegueWithIdentifier:@"showPhotoTypeSelector" sender:nil];
    } else if (indexPath.section == CellTypePhotos) {
        UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"Main" bundle:nil];
        
        PhotoResizerViewController *photoResizer = [storyboard instantiateViewControllerWithIdentifier:@"PhotoResizer"];
        photoResizer.photoManager = self.photosManager;
        photoResizer.photo        = [self.photosManager getPhotoAtIndex:indexPath.row];
        photoResizer.tableView    = tableView;
        
        [self.navigationController presentViewController:photoResizer animated:YES completion:^{
            
        }];
    }
}

- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the specified item to be editable.
    return NO;
}

- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        //[self.objects removeObjectAtIndex:indexPath.row];
        //[tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
    } else if (editingStyle == UITableViewCellEditingStyleInsert) {
        // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view.
    }
}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    
}

#pragma mark - Buttons Actions
- (IBAction)addPhotosTapped:(id)sender {
    [self performSegueWithIdentifier:@"showPhotoPicker" sender:nil];
}

- (void)tapUpButton:(id)sender {
    UIView *view =  ((UIButton*)sender).superview.superview.superview.superview;
    if ([view isKindOfClass:[PhotoListTableViewCell class]]) {
        [((PhotoListTableViewCell*)view) increasePhotoNumber];
    }
}

- (void)tapDownButton:(id)sender {
    UIView *view =  ((UIButton*)sender).superview.superview.superview.superview;
    if ([view isKindOfClass:[PhotoListTableViewCell class]]) {
        [((PhotoListTableViewCell*)view) decreasePhotoNumber];
    }
}

- (IBAction)rightButtonTapped:(id)sender {
    [self performSegueWithIdentifier:@"showOrderList" sender:sender];
}

#pragma mark - synthethizer
- (PFPhotosManager*)photosManager {
    if (photosManager == nil) {
        photosManager = [[PFPhotosManager alloc] initFromLocalStorage];
    }
    return photosManager;
}

@end
